#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 100000;
struct node
{
    int index, data, next;
    node (){
        index = next = -1;
        data = (1 << 31);//出错的原因是：测试用例当中有最大值也有最小值
    }
} nod[MAXN];
bool cmp(node ll, node rr)
{//不要用>=，因为可能导致越界行为发生，暂时还不知道为什么
    return ll.data < rr.data;
}
//If the return statement was return xxx >= xxx or xxx <= xxx ; 
//and you used a smaller range of values, it too would probably crash.
int main()
{
    int N, first;
    //printf("%d %d %d\n", nod->data, nod->index, nod->next);//test
    scanf("%d%d", &N, &first);
    int i;
    int addr;
    for (i = 0; i < N; ++i)
    {
        scanf("%d", &addr);
        nod[addr].index = addr;
        scanf("%d%d", &nod[addr].data, &nod[addr].next);
    }
    int count = 0;//记录有效节点个数
    int tmaddr = first;
    while(tmaddr != -1)
    {//从开始节点开始遍历，同时标记有效结点
        tmaddr = nod[tmaddr].next;
        ++count;
    }
    if(0 == count)
    {//特判，全为无效结点
        printf("0 -1\n");
        return 0;
    }
    sort(nod, nod + MAXN, cmp);
    printf("%d %05d\n", count, nod[MAXN -count].index);
    for (i = MAXN - count; i < MAXN -1; ++i)
    {
        printf("%05d %d %05d\n", nod[i].index, nod[i].data, nod[i + 1].index);
    }
    printf("%05d %d -1\n", nod[i].index, nod[i].data);
    return 0;
}